import Vue from 'vue'
import Vuex from 'vuex'
import {
  initNavbars,
  shopDetails,
  shopList,
  login,
  getuserInfo,
  userLogout,
  userRegister,
  searchGoods,
  updateName,
  updatePhone,
  updateGxqm,
  updatePwd,
  getWeather,
  updateZxb,
  inituserAddress,
  saveAddress,
  updateDefaultAddress,
  rechargeUserMoney
} from '../api'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    token:sessionStorage.getItem("token") || "",
    categories:[],
    merchantGoods:[],
    merchantInfo:{},
    ratings:[],
    userMap:{},
    cartFoods:[] //购物车食物的列表
  },
  getters: {
    totalPrice(state){
        return state.cartFoods.reduce((preTotal,food)=>preTotal+food.count*food.price,0)
    },
    totalCount(){
        return state.cartFoods.reduce((preTotal,food)=>preTotal+food.count,0)
    }
  },
  mutations: {
      SET_TOKEN(state,token){
            state.token=token
      },
      SAVE_FOODCATEGORYS(state,dataList){
          state.categories=dataList
      },
      SAVE_SHOPDETAILS(state,dataMap){
          state.merchantGoods=dataMap.goods
          state.merchantInfo=dataMap.info
          state.ratings=dataMap.ratings
      },
      SAVE_SHOPLIST(state,dataList){
          state.shopList=dataList
      },
      SAVE_USERINFO(state,dataMap){
          state.userMap=dataMap
      },
      LogOut(state){
          state.token=""
          state.userMap={}
      },
    //   增加食物的数量
      INCREAMENT_FOOD_COUNT(state,{food}){
        if(!food.count){ 
            // food.count=1 //新增属性（没有数据绑定）
            // 新增的属性也有数据绑定
            Vue.set(food,"count",1) //Vue有一个方法 set /对象  属性名  值/
            state.cartFoods.push(food)
        }else {
            food.count++
        }
      },
      DECREMENT(state,{food}){
        if(food.count){
            food.count--
        }
        if(food.count==0){
            // 将food从foodcarts中移除
            state.cartFoods.splice(state.cartFoods.indexOf(food),1)
        }
      }
  },
  actions: {
      async UserLogin({commit},data){
        const res=await login(data)
        if(res.code==0){
            sessionStorage.setItem("token",res.token)
            commit("SET_TOKEN",res.token)
            return true
        }else {
            return false
        }
      },
      async UserReg({commit},data){
          const res=await userRegister(data)
          if(res.code==0){
              return true
          }else if(res.code==1){
              return 301
          }
      },
      // 加载用户信息
      async LoaduserInfo({commit}){
        const res=await getuserInfo()
        commit("SAVE_USERINFO",res.data.dataMap)
      },
      // 退出登录
      async Logout({commit}){
          const res=await userLogout()
          if(res.code==0){
              commit("LogOut")
              sessionStorage.removeItem("token")
              return true
          }
      },
    //   用户修改密码
      async userUpdatePwd({commit},params){
        const res=await updatePwd(params)
        return res
      },
      async LoadFoodCategorys({commit}){
          const res=await initNavbars()
          res.data.dataList.forEach((valMap,index)=>{
              valMap["id"]=index+1
          })
          commit("SAVE_FOODCATEGORYS",res.data.dataList)
      },
      async initShopDetails({commit},data){
          const res=await shopDetails(data)
          commit("SAVE_SHOPDETAILS",res)
      },
      async initShopList({commit}){
          const res=await shopList()
          res.forEach(valMap=>{
              valMap["image_path"]="/images/avatar/"+Math.ceil(Math.random()*4)+".jpg"
          })
          commit("SAVE_SHOPLIST",res)
      },
        // 搜索关键字
      async searchKeywords({commit},data){
            const res=await searchGoods(data)
            res.data.dataList.forEach((valMap,index)=>{
                valMap["id"]=index+1
            })  
            return res.data.dataList
      },
        //修改昵称
      async UpdateSkinName({commit},skinName){
        const data={skinName}
        const res=await updateName(data)
        if(res.code==0){
            return true
        }else {
            return false
        }
      },
    //   修改手机号
    async UPDATEphone({commit},phone){
        const data={phone}
        const res=await updatePhone(data)
        if(res.code==0){
            return true
        }else {
            return false
        }
    },
    // 修改个性签名
    async UPDATEgxqm({commit},gxqm){
        const data={gxqm}
        const res=await updateGxqm(data)
        if(res.code==0){
            return true
        }else {
            return false
        }
    },
    // 加载天气
    async loadWeather({commit},dataMap){
        const results=await getWeather(dataMap)
        return results
    },
    // 修改紫星币数量
    async updateZxbNum({commit},dataMap){
        const results=await updateZxb(dataMap)
        if(results.code==0){
            return true
        }else {
            return false
        }
    },
    // 加载用户收货地址
    async loaduserAddress({commit}){
        const res=await inituserAddress()
        res.data.dataList.forEach((item,index)=>{
            item["id"]=index+1
        })
        return res.data.dataList
    },
    // 保存用户收货地址信息
    async SaveUserAddress({commit},Map){
        const response=await saveAddress(Map)
        return response
    },
    // 修改默认收货地址
    async UpdateDefaultRess({commit},Map){
        const res=await updateDefaultAddress(Map)
        if(res.code==0){
            return true
        }else {
            return false
        }
    },
    // 同步更新food中的count中
    updateFoodCount({commit},{isAdd,food}){
        if(isAdd){
            commit("INCREAMENT_FOOD_COUNT",{food})
        }else {
            commit("DECREMENT",{food})
        }
    },
    // 用户充值余额
    async rechargeMoney({commit},dataMap){
        const result=await rechargeUserMoney(dataMap)
        return result.code
    }
  },
  modules: {
    
  }
})
